package com.ai.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.util.Random;

public class TestPasswordSalt {
    private static final String S_SALT = "1a2b3c4d5e";

    /**
     * 生成含有随机盐的密码
     *
     * @param password 要加密的密码
     * @return String 含有随机盐的密码
     */
    public static String getSaltMD5(String password, String salt) {
        password = DigestUtils.md5Hex(password + S_SALT);
        password = DigestUtils.md5Hex(salt + password);
        return password;
    }

    public static String randomString(int length) {
        //定义一个字符串(a-z,A-Z,0-9)
        String str = "ZXCVBNMASDFGHJKLQWERTYUIOPzxcvbnmasdfghjklqwertyuiop0123456789";
        System.out.println(str.length());

        // 生成一个16位的随机数
        Random random = new Random();
        StringBuilder sBuilder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sBuilder.append(str.charAt(number));
        }
        // 生成最终的加密盐
        return sBuilder.toString();
    }

    public static void main(String[] args) {
        // 原密码
        String plaintext = "123456";
        String salt = randomString(16);
        // 获取加盐后的MD5值
        String ciphertext = TestPasswordSalt.getSaltMD5(plaintext, salt);
        System.out.println("加盐后MD5：" + ciphertext);


        String new_plaintext = "123456";
        // 获取加盐后的MD5值
        String new_ciphertext = TestPasswordSalt.getSaltMD5(new_plaintext, salt);
        System.out.println(ciphertext.equals(new_ciphertext));
    }
}